#include <stdlib.h>
#include <stdio.h>
#include <setjmp.h>
#include "hpdf.h"

jmp_buf env;

void error_handler(HPDF_STATUS error_no, HPDF_STATUS detail_no, void* user_data) {
    printf("ERROR: error_no=%04X, detail_no=%u\n", (HPDF_UINT)error_no, (HPDF_UINT)detail_no);
    longjmp(env, 1);
}

int main(void) {
    // Specify the input PNG file and output PDF file paths
    const char* input_filename = "path/to/input.png";
    const char* output_filename = "path/to/output.pdf";

    HPDF_Doc pdf;
    HPDF_Page page;

    pdf = HPDF_New(error_handler, NULL);
    if (!pdf) {
        printf("error: cannot create PdfDoc object\n");
        return 1;
    }

    if (setjmp(env)) {
        HPDF_Free(pdf);
        return 1;
    }

    HPDF_SetCompressionMode(pdf, HPDF_COMP_ALL);

    page = HPDF_AddPage(pdf);
    HPDF_Page_SetWidth(page, 595);  // A4 width
    HPDF_Page_SetHeight(page, 842); // A4 height

    HPDF_Image image = HPDF_LoadPngImageFromFile(pdf, input_filename);

    float page_width = HPDF_Page_GetWidth(page);
    float page_height = HPDF_Page_GetHeight(page);
    float img_width = HPDF_Image_GetWidth(image);
    float img_height = HPDF_Image_GetHeight(image);

    float x = (page_width - img_width) / 2;
    float y = (page_height - img_height) / 2;

    HPDF_Page_DrawImage(page, image, x, y, img_width, img_height);

    HPDF_SaveToFile(pdf, output_filename);
    HPDF_Free(pdf);

    return 0;
}